<?php
if ( !defined( 'BIGCKOOL_VERSION' ) ) {
	header( 'HTTP/1.0 403 Forbidden' );
	die;
}

class BIGCKOOL_Frontend {
	private $user; 
	private $fbloginUrl;
	private $uservoted=false;
	private $userlikedFP;
	private $FB;
	function __construct() {
		
		
		$optionfb=get_option('bigckool_option_fb');
		//bct($_SERVER);
		if($this->checkapp()!='canvas'){
			//wp_redirect( $optionfb['app_url'] ); exit;
		}
	  
		require_once(BIGCKOOL_PATH . 'facebook-php-sdk/facebook.php');			
			$config = array(
		      'appId' => $optionfb['app_id'],
		      'secret' => $optionfb['app_secret'],
				'cookie' => true
		  );
		  $this->userlikedFP=false;
	  	$this->FB = new Facebook($config);  
		
	  	bigckool_logUser("begin check user");
		$this->checkFBUserLogin();
		
		//filter to log user in post
		add_action('the_content',array($this,'logUserInPost'));
	    
		if(isset($_POST['postid']))
			$this->submitVote();
			
	
	}
	function isVoted(){
		return $this->uservoted;
	}
	function getUser(){
		return $this->user;
	}
	

	function submitVote($postid=0){		
		$isSuccess=0; 	
		$user=$this->user;		
		if($postid>0 && !is_null($user) && isset($user->ID) && intval($user->ID)>0){
			//update_post_meta
			$postvote=get_post_meta($postid,'vote',1);			
			$votecount=intval(get_post_meta($postid,'votecount',1));
			if(empty($postvote)){
				$postvote=array();
			}
			//if userid not in array key then user not vote
			if(!array_key_exists($user->ID, $postvote)){
				try{
					$postvote[$user->ID]['time']=time();
					update_post_meta($postid,'vote',$postvote);
					update_post_meta($postid,'votecount',$votecount+1);
					//update user
					$arrpost=get_user_meta($user->ID,'vote',1);
					if(empty($arrpost)){
						$arrpost=array();
					}
					if(!array_key_exists($postid, $arrpost)){
						$arrpost[$postid]['time']=time();
						update_user_meta($user->ID, 'vote', $arrpost);
					}	
					$isSuccess=1;
					//bct(get_post_meta($postid,'vote',1));
				}
				catch (Exception $e){
					bigckool_logUser("error when submit vote with userid:".$user->ID." and postid:".$postid." message:".$e->getMessage());
				}
			}
		}
		if($isSuccess){
			bigckool_logUser("userid ".$user->ID." voted postid ".$postid);
			echo "success";
		}
		
	}
	
	function logUserInPost($data){
		global $post;
		if(is_single()){			
			$postid=intval($post->ID);			
			if($postid>0){
				$user=$this->user;
				if(!empty($user) && !empty($user->ID)){		
					$postvote=get_post_meta($postid,'vote',1);		
					if(empty($postvote)){
						$postvote=array();
					}
					//if userid exist in array then user already post
					$logcontent="userid ".$user->ID." in postid ".$post->ID;
					if (array_key_exists($user->ID, $postvote)){
						$this->uservoted=true;
						$logcontent.=" and voted";	
					}
					bigckool_logUser($logcontent);
				}
				else{
					$log_content = 'Không lấy được thông tin người dùng khi kiểm tra vote cho bài dự thi với ID ' . $postid;
					bigckool_logMissingUser($log_content);
				}
			}
		}
		return $data;
	}
	function getFBLoginUrl(){
		return $this->fbloginUrl;
	}
	function parse_signed_request($signed_request, $secret) {
	    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	
	    // decode the data
	    $sig = $this->base64_url_decode($encoded_sig);
	    $data = json_decode($this->base64_url_decode($payload), true);
	
	    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
	        error_log('Unknown algorithm. Expected HMAC-SHA256');
	        return null;
	    }
	
	    // check sig
	    $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
	    if ($sig !== $expected_sig) {
	        error_log('Bad Signed JSON signature!');
	        return null;
	    }
	
	    return $data;
	}
	
	function base64_url_decode($input) {
	    return base64_decode(strtr($input, '-_', '+/'));
	}
	function checkapp(){
		if(!isset($_SESSION)) {
	     session_start();
		}
		//check session for mobile
		if(isset($_GET['m']) || DEBUG > 0)$_SESSION['m']=true;
		if(isset($_SESSION['fbcavas']) && $_SESSION['fbcavas']==1)return "canvas";
		else if( isset($_REQUEST['signed_request']) ) {
		    // We are in Canvas or Page now
		
		    // Let's extract the data from the signed_request 
		    // to check if we are inside a Facebook Page
		    $app_secret = "APP_SECRET";
		    $data = $this->parse_signed_request($_REQUEST["signed_request"], $app_secret);
		
		    if( isset($data["page"]) ) {
		        return "page";
		    } else {
		    	$_SESSION['fbcavas']=1;
		        return "canvas";
		    }
		} else {
		    return "None, or something went wrong!";
		}
	}	
	function checkFBUserLogin(){
		$optionfb=get_option('bigckool_option_fb');		
		$user = $this->FB->getUser();
		$loginredirect=$optionfb['app_url'].$_SERVER['REQUEST_URI'];
		if(isset($_SESSION['m']))$loginredirect=home_url('/');
	    $loginUrl   = $this->FB->getLoginUrl(
	            array(
	                'scope'         => 'email,publish_actions,user_birthday,user_likes',
	                'redirect_uri' =>$loginredirect
	            )
	    ); 
	    
	    if ($user) {
	      try {		  
	        // Proceed knowing you have a logged in user who's authenticated.
	        $user_profile = $this->FB->api('/me');
	      } catch (FacebookApiException $e) {
			bigckool_logError($e->getMessage().' Get FB api again.');
		  //get FB session again			
			$config = array(		      
				'appId' => $optionfb['app_id'],		      
				'secret' => $optionfb['app_secret'],				
				'cookie' => true			);			
			$this->FB = new Facebook($config);			
			try{				
				$user_profile = $this->FB->api('/me');						
			} catch (FacebookApiException $e) {		
				bigckool_logError($e->getMessage().' Refresh page');
				echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
				exit;			
			}
	        //you should use error_log($e); instead of printing the info on browser			
			//echo "<script type='text/javascript'>top.location.href = '.$optionfb['app_url'].';</script>";
	        //die($e);  // d is a debug function defined at the end of this file
	        //$user = null;
	      }
	    }	 
	    if (!isset($user_profile) || empty($user_profile)) {
	        echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
	        $this->fbloginUrl=$loginUrl;
	        exit;
	    }
	    else{
	    	//save user    	
	    	//$user_profile = $facebook->api('/me');
	    	$this->saveFBUser($user_profile);
	    	
			//bct($this->FB->getAccessToken());
	    	$domain='https://'.$_SERVER['SERVER_NAME'];			  
    		$requesturls=split('\?',$_SERVER['REQUEST_URI']);
			$requesturl=$requesturls[0];
			
	    	//check user like fanpage	  
			try {		
				$signed_request = $this->FB->api('/me/likes/'.$optionfb['fanpage_id'].'');
			} catch (FacebookApiException $e) {	
				if(!strrpos($requesturl,'refresh=true')){
					bigckool_logError($e->getMessage().' Refresh page');
					echo "<script type='text/javascript'>top.location.href = '".$domain.$requesturl."?refresh=true';</script>";
					
				}
			}
	    	
			if(empty($signed_request['data'])){	    		
			  if($domain.$requesturl!=home_url('/') && $domain.$requesturl!=home_url('/the-le/') ){
	    		wp_redirect( home_url('/?r='.$_SERVER['REQUEST_URI']) ); exit;
			  }
	    	}
	    	else{
	    		$this->userlikedFP=true;
	    		if($domain.$requesturl==home_url('/')&& !isset($_GET['s'])){
	    			wp_redirect('/category/tuan1/');
	    			exit;
	    		}
	    	}
	    }		
	}
	function saveFBUser($fbuser){	
		bigckool_logUser("check user with fbid \"".$fbuser['id']."\" is exist?");		
		$args = array(					 		
				'orderby' => 'id',
				'order' => 'DESC',
				'meta_query' => array(
			       array(
			           'key' => 'fbid',
			           'value' => $fbuser['id'],
			           'compare' => '==',
			       )
			   )							
			);								
		$users= get_users($args);
		if(count($users)==0){
			$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
			$user_id = wp_create_user ( $fbuser['id'] , $random_password, $fbuser['email'] );
			add_user_meta( $user_id, 'gender', $fbuser['gender'],1 );
			add_user_meta( $user_id, 'link', $fbuser['link'] ,1);
			add_user_meta( $user_id, 'birthday', $fbuser['birthday'],1 );
			add_user_meta( $user_id, 'fbid', $fbuser['id'],1 );
			add_user_meta( $user_id, 'fbname', $fbuser['name'],1 );
			$location='';
			if(isset($fbuser['location']['name']))
				$location=$fbuser['location']['name'];
			add_user_meta( $user_id, 'location',$location,1 );  
			bigckool_logUser("user with fbid \"".$fbuser['id']."\" was created.");
		}
		else{
			bigckool_logUser("user exist. Get user.");
		}
		$users= get_users($args);
		if(count($users)>0){
			$user=$users[0];
			$usermeta['gender']=get_user_meta($user->ID,'gender',1);	
			$usermeta['link']=get_user_meta($user->ID,'link',1);
			$usermeta['birthday']=get_user_meta($user->ID,'birthday',1);
			$usermeta['location']=get_user_meta($user->ID,'location',1);
			$usermeta['fbid']=get_user_meta($user->ID,'fbid',1);
			$usermeta['vote']=get_user_meta($user->ID,'vote',1);
			$user->meta=$usermeta;
			$this->user=$user;	
			$_SESSION["userid"]=$user->ID;
			$log_content="saved userid ".$_SESSION["userid"]." into session";
			bigckool_logUser($log_content);
		}
		else{
			bigckool_logUser("Cannot get user with username \"".$fbuser['name']."\" and fbid ".$fbuser['id']);		
		}
		
	}
	function isUserLikeFP(){
		return $this->userlikedFP;
	}
}
global $bigckool_frontend;
$bigckool_frontend = new BIGCKOOL_Frontend();
?>